package dbs

import (
	"github.com/jinzhu/gorm"
	"time"
)

type DbFile struct {
	ID        uint      `json:"id" gorm:"primary_key"`
	Hash      string    `json:"hash" gorm:"type:varchar(64);not null;unique"`
	Name      string    `json:"file_name" gorm:"type:varchar(255)"`
	Value     []byte    `json:"value" gorm:"type:longblob"`
	CreatedAt time.Time `json:"created_at" gorm:"type:datetime"`
}

func (self *DbFile) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Create(&self).Error
	})
	return
}

func (self *DbFile) Exit() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		err = conn.Where("hash = ?", self.Hash).Select("id,hash").Find(&self).Error
		return
	})
	return
}

func (self *DbFile) Get() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.Hash != "" {
			conn = conn.Where("hash = ?", self.Hash)
		}

		return conn.Find(&self).Error
	})
	return
}

func (self *DbFile) Delete() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if self.Hash != "" {
			conn = conn.Where("hash = ?", self.Hash)
		}
		return conn.Delete(&self).Error
	})
	return
}

func (self *DbFile) DeleteRaw(db *gorm.DB) (err error) {
	if self.Hash != "" {
		db = db.Where("hash = ?", self.Hash)
		return db.Delete(&self).Error
	}
	return
}
